#!/usr/bin/env python3
"""
GUI+Web预览监控器演示脚本
展示如何复刻 hybrid_preview_monitor.py 的功能
"""

import sys
import os
import numpy as np
from PIL import Image
import time
import threading

def create_demo_images():
    """创建演示图片"""
    images = []
    
    # 创建不同颜色的测试图片
    colors = [
        (255, 0, 0),    # 红色
        (0, 255, 0),    # 绿色
        (0, 0, 255),    # 蓝色
        (255, 255, 0),  # 黄色
        (255, 0, 255),  # 紫色
        (0, 255, 255),  # 青色
    ]
    
    for i, color in enumerate(colors):
        # 创建512x512的图片
        img = np.zeros((512, 512, 3), dtype=np.uint8)
        img[:, :] = color
        
        # 添加文字标识
        pil_img = Image.fromarray(img)
        # 这里可以添加文字，但为了简化，直接返回numpy数组
        
        images.append(img)
        print(f"✅ [DEBUG] Created demo image {i+1}: {color}")
    
    return images

def demo_simple_gui():
    """演示简化版GUI"""
    print("🎯 [DEMO] Starting Simple GUI Preview Monitor Demo...")
    
    try:
        from simple_gui_preview import SimpleGUIPreviewMonitor
        
        # 创建演示图片
        demo_images = create_demo_images()
        
        # 创建GUI应用
        app = SimpleGUIPreviewMonitor()
        app.add_images(demo_images)
        
        print("✅ [DEMO] Simple GUI Preview Monitor started!")
        print("📋 [DEMO] Controls:")
        print("   - Left/Right arrows: Navigate images")
        print("   - R: Reset view")
        print("   - Mouse wheel: Zoom")
        print("   - Mouse drag: Pan")
        print("   - Close window to exit")
        
        # 运行应用
        app.run()
        
    except ImportError as e:
        print(f"❌ [ERROR] Import error: {e}")
        print("Please install required dependencies:")
        print("pip install pywebview")
    except Exception as e:
        print(f"❌ [ERROR] Demo failed: {e}")
        import traceback
        traceback.print_exc()

def demo_full_gui():
    """演示完整版GUI"""
    print("🎯 [DEMO] Starting Full GUI Preview Monitor Demo...")
    
    try:
        from gui_web_preview_monitor import GUIPreviewMonitor
        
        # 创建演示图片
        demo_images = create_demo_images()
        
        # 模拟ComfyUI节点调用
        result = GUIPreviewMonitor.display_image(
            images=demo_images,
            mode="new",
            monitor="Monitor 0",
            power_state="On",
            fit_mode="fit",
            target_resolution="1920x1080",
            gain=1.0,
            gamma=1.0,
            saturation=1.0,
            white_matte=False,
            fps_mode="smart",
            cpu_mode=True,
            high_quality=True
        )
        
        print("✅ [DEMO] Full GUI Preview Monitor started!")
        print("📋 [DEMO] Features:")
        print("   - High-performance image display")
        print("   - WebSocket communication")
        print("   - Advanced controls")
        print("   - Multi-monitor support")
        print("   - Video playback support")
        
        # 等待用户交互
        input("Press Enter to continue...")
        
        # 清理
        GUIPreviewMonitor.cleanup_all_windows()
        print("✅ [DEMO] Cleanup completed")
        
    except ImportError as e:
        print(f"❌ [ERROR] Import error: {e}")
        print("Please install required dependencies:")
        print("pip install PyQt5 PyQtWebEngine websockets opencv-python")
    except Exception as e:
        print(f"❌ [ERROR] Demo failed: {e}")
        import traceback
        traceback.print_exc()

def show_comparison():
    """显示功能对比"""
    print("📊 [COMPARISON] GUI+Web方案 vs 原版Pygame方案")
    print("=" * 60)
    
    features = [
        ("图片显示性能", "✅ 优秀", "✅ 优秀", "原生渲染引擎"),
        ("实时交互响应", "✅ 60fps", "✅ 60fps", "硬件加速"),
        ("UI界面灵活性", "❌ 有限", "✅ 优秀", "HTML/CSS/JS"),
        ("开发扩展性", "❌ 有限", "✅ 优秀", "Web技术栈"),
        ("跨平台兼容性", "✅ 好", "✅ 优秀", "统一界面"),
        ("开发维护成本", "❌ 高", "✅ 低", "标准技术"),
        ("功能完整性", "✅ 完整", "✅ 完整", "完全复刻"),
        ("用户体验", "✅ 好", "✅ 优秀", "现代化界面"),
    ]
    
    print(f"{'功能':<15} {'原版Pygame':<12} {'GUI+Web':<12} {'优势'}")
    print("-" * 60)
    
    for feature, original, new, advantage in features:
        print(f"{feature:<15} {original:<12} {new:<12} {advantage}")
    
    print("=" * 60)
    print("🎯 [CONCLUSION] GUI+Web方案是原版功能的完美升级！")

def main():
    """主函数"""
    print("[GUI+Web Preview Monitor Demo]")
    print("复刻 hybrid_preview_monitor.py 的功能")
    print("=" * 50)
    
    while True:
        print("\n[MENU] 选择演示方案:")
        print("1. 简化版GUI (tkinter + pywebview)")
        print("2. 完整版GUI (PyQt5 + QWebEngineView)")
        print("3. 功能对比")
        print("4. 退出")
        
        choice = input("\n请选择 (1-4): ").strip()
        
        if choice == "1":
            demo_simple_gui()
        elif choice == "2":
            demo_full_gui()
        elif choice == "3":
            show_comparison()
        elif choice == "4":
            print("[GOODBYE] 感谢使用！")
            break
        else:
            print("[ERROR] 无效选择，请重新输入")

if __name__ == "__main__":
    main()
